package com.getpebble.android.framework.pebblekit;

import android.content.Context;
import android.content.Intent;
import android.util.Base64;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.model.PblDeviceModel.PblDeviceRecord;
import com.getpebble.android.framework.analytics.WatchAnalytics;
import com.getpebble.android.framework.appmessage.AppMessage;
import com.getpebble.android.framework.appmessage.AppMessage.AppMessageCommand;
import com.getpebble.android.framework.appmessage.JsonPebbleDictionary;
import com.getpebble.android.framework.datalogging.DataloggingItem;
import com.getpebble.android.framework.datalogging.DataloggingSession;
import com.getpebble.android.framework.developer.PblDeviceObserver.ConnectedDeviceChangeListener;
import com.getpebble.android.framework.protocol.inbound.PblInboundAppMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage.ByteDataItem;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage.Datatype;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage.SignedIntDataItem;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage.UnsignedIntDataItem;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;

public class PebbleKit implements ConnectedDeviceChangeListener {
    private static final String TAG = PebbleKit.class.getSimpleName();
    private static PebbleKit sInstance;
    private List<PblDeviceRecord> mConnectedDevices;
    private final Context mContext;

    static /* synthetic */ class AnonymousClass1 {
        static final /* synthetic */ int[] $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Datatype = new int[Datatype.values().length];

        static {
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Datatype[Datatype.BYTE_ARRAY.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Datatype[Datatype.UNSIGNED_INTEGER.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Datatype[Datatype.SIGNED_INTEGER.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
        }
    }

    public void notifyConnectedDeviceChanged() {
        handleConnectionChange();
    }

    PebbleKit(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("context cannot be null");
        }
        Trace.debug(TAG, "PebbleKit()");
        this.mContext = context;
        this.mConnectedDevices = new ArrayList();
        PebbleApplication.addConnectedDeviceChangeListener(this);
    }

    public void destroy() {
        PebbleApplication.removeConnectedDeviceChangeListener(this);
    }

    protected PblDeviceRecord getConnectedDeviceRecord() {
        return PebbleApplication.getConnectedDeviceRecord();
    }

    private void handleConnectionChange() {
        PblDeviceRecord connectedDevice = getConnectedDeviceRecord();
        if (!(connectedDevice == null || this.mConnectedDevices.contains(connectedDevice))) {
            Trace.verbose(TAG, "Broadcasting CONNECTED Intent for " + connectedDevice.pblDevice);
            Intent intent = new Intent("com.getpebble.action.PEBBLE_CONNECTED");
            intent.putExtra("address", connectedDevice.pblDevice.getAddress());
            this.mContext.sendBroadcast(intent);
        }
        for (PblDeviceRecord previouslyConnectedDevice : this.mConnectedDevices) {
            if (!previouslyConnectedDevice.equals(connectedDevice)) {
                Trace.verbose(TAG, "Broadcasting DISCONNECTED Intent for " + previouslyConnectedDevice.pblDevice);
                intent = new Intent("com.getpebble.action.PEBBLE_DISCONNECTED");
                intent.putExtra("address", previouslyConnectedDevice.pblDevice.getAddress());
                this.mContext.sendBroadcast(intent);
            }
        }
        this.mConnectedDevices.clear();
        if (connectedDevice != null) {
            this.mConnectedDevices.add(connectedDevice);
        }
    }

    public static synchronized PebbleKit getInstance(Context context) {
        PebbleKit pebbleKit;
        synchronized (PebbleKit.class) {
            if (sInstance == null) {
                sInstance = new PebbleKit(context);
            }
            pebbleKit = sInstance;
        }
        return pebbleKit;
    }

    public void broadcastDataloggingItem(DataloggingItem item) {
        try {
            Intent intent = new Intent("com.getpebble.action.dl.RECEIVE_DATA_NEW");
            intent.putExtra("pbl_data_id", item.getDataId());
            intent.putExtra("pbl_data_type", item.getSession().getDataType().getCode());
            switch (AnonymousClass1.$SwitchMap$com$getpebble$android$framework$protocol$inbound$PblInboundDataloggingMessage$Datatype[item.getSession().getDataType().ordinal()]) {
                case SMTPMessage.RETURN_FULL /*1*/:
                    intent.putExtra("pbl_data_object", Base64.encodeToString(((ByteDataItem) item.getDataObject()).getValue(), 2));
                    break;
                case SMTPMessage.RETURN_HDRS /*2*/:
                    intent.putExtra("pbl_data_object", Long.valueOf(((UnsignedIntDataItem) item.getDataObject()).getValue().longValue()));
                    break;
                case ListInfo.INDETERMINATE /*3*/:
                    intent.putExtra("pbl_data_object", ((SignedIntDataItem) item.getDataObject()).getValue());
                    break;
                default:
                    Trace.warning(TAG, "Unknown data type: " + item.getSession().getDataType());
                    return;
            }
            intent.putExtra("uuid", item.getSession().getAppUuid());
            intent.putExtra("data_log_uuid", item.getSession().getLocalSessionUuid());
            intent.putExtra("data_log_timestamp", Long.valueOf(item.getSession().getTimestampSecs().longValue()));
            intent.putExtra("data_log_tag", Long.valueOf(item.getSession().getAppLogTag().longValue()));
            if (WatchAnalytics.WATCH_ANALYTICS_APP_UUID.equals(item.getSession().getAppUuid()) && WatchAnalytics.WATCH_ANALYTICS_TAG.equals(item.getSession().getAppLogTag())) {
                Trace.verbose(TAG, "Watch analytics; not broadcasting Intent - forwarding");
                intent.setClass(this.mContext, WatchAnalytics.class);
                this.mContext.startService(intent);
                return;
            }
            this.mContext.sendBroadcast(intent);
        } catch (Exception e) {
            Trace.warning(TAG, "Error sending datalogging data item", e);
        }
    }

    public void broadcastDataloggingCloseSession(DataloggingSession session) {
        try {
            Intent intent = new Intent("com.getpebble.action.dl.FINISH_SESSION_NEW");
            intent.putExtra("uuid", session.getAppUuid());
            intent.putExtra("data_log_timestamp", Long.valueOf(session.getTimestampSecs().longValue()));
            intent.putExtra("data_log_tag", Long.valueOf(session.getAppLogTag().longValue()));
            intent.putExtra("data_log_uuid", session.getLocalSessionUuid());
            this.mContext.sendBroadcast(intent);
        } catch (Exception e) {
            Trace.warning(TAG, "Error sending datalogging session closure message", e);
        }
    }

    public boolean handleAppMessage(PblInboundAppMessage inboundAppMessage) {
        AppMessage appMessage = inboundAppMessage.getAppMessage();
        if (appMessage == null || appMessage.getCommand() == null) {
            Trace.warning(TAG, "missing or malformed appmessage");
            return false;
        }
        Intent i;
        AppMessageCommand command = appMessage.getCommand();
        if (command == AppMessageCommand.PUSH) {
            i = new Intent("com.getpebble.action.app.RECEIVE");
            try {
                String jsonDictionary = new JsonPebbleDictionary(appMessage.getPebbleDictionary()).toJsonLegacyStyle();
                i.putExtra("uuid", appMessage.getUuid());
                i.putExtra("msg_data", jsonDictionary);
            } catch (JSONException e) {
                Trace.debug(TAG, "Could not marshal response from watch");
                return false;
            }
        } else if (command == AppMessageCommand.ACK) {
            i = new Intent("com.getpebble.action.app.RECEIVE_ACK");
        } else if (command == AppMessageCommand.NACK) {
            i = new Intent("com.getpebble.action.app.RECEIVE_NACK");
        } else {
            Trace.error(TAG, "received unsupported AppMessage command:" + command);
            return false;
        }
        i.putExtra("transaction_id", appMessage.getTransactionId() & 255);
        Trace.debug(TAG, "About to broadcast AppMessage: " + i.toString());
        this.mContext.sendBroadcast(i);
        return true;
    }
}
